﻿package com.cilico.components;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.Typeface;
import android.graphics.drawable.Drawable;
import android.text.TextPaint;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.View;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.cilico.ConfigManager;
import com.cilico.R;
import com.cilico.utils.ConstantRepository;
import com.cilico.utils.DrawableFactory;
import com.cilico.utils.Utils;
import com.cilico.utils.StringTicker;
import com.cilico.view.BaseView;
import com.cilico.view.FormLayout;

/**
 * 按钮控件
 * @author lv.xiangan
 *
 */
public class mButton extends TextView implements Component {
	// 二级界面控件判断标志
	private boolean isSubmenu_;
	private boolean isFirstSubmenu_;
	private boolean isLastSubmenu_;
	// 二级界面显示的背景图片，由于所有的二级界面显示的背景图片一致，所以就所有该控件共用一个bitmap对象
	static Bitmap BACKGROUND1;
	static Bitmap BACKGROUND2;
	static Bitmap BACKGROUND3;
	static Bitmap BACKGROUNDSEL1;
	static Bitmap BACKGROUNDSEL2;
	static Bitmap BACKGROUNDSEL3;
	private Bitmap iconBitmap = null;
	
	private static final int DEFAULT_BUTTON_UP_COLOR = 0xff346fbc;
	private static final int DEFAULT_BUTTON_DOWN_COLOR = 0xff000000;
	private static final int DEFAULT_BUTTON_FOCUS_COLOR = 0xffff0000;
	// 控件样式对象
	public CssStyle cssStyle_;
	public CssStyle pseudoStyle_;
	private static int styleIndex_;
	public static int NORMAL_IMG = 0;
	public static int DOWN_IMG = 1;
	public static int FOCUS_IMG = 2;
	private Bitmap focusButton_;
	private Bitmap upButton_;
	private Bitmap downButton_;
	public BaseView bv_;
	String isEncrypt_;
	public String attrName_;
	public String attrValue_;
	public String buttonType_; // submit/reset/cancel/button
	public boolean isNoCancel_ = false; // Indicate that this submit can not cancel
	public boolean focus_ = false;
	public boolean isTopChannelAlone_ = false; // 只有一个二级菜单

	boolean isSinglePng;
	boolean isRollNotStopB_ = false;
	protected TextPaint font_;

	ComponentListener listener_;

	int left_;
	int top_;
	private int height_;
	private int width_;

	private int textColor_;
	int clickedColor_;
	int clickedBgColor_;

	public String accessory_;
	public static final String BTN_ACT_ADD = "add";
	public static final String BTN_ACT_DEL = "del";
	public static final String BTN_ACT_CONFIRM = "confirm";
	public String buttonAction_;
	private Drawable[] upDrawable_;
	private Drawable[] downDrawable_;
	private Drawable[] focusDrawable_;

	private boolean isDown_;
	private boolean isInTable_;
	private LinearLayout selfLayout_;
	private FormLayout formLayout_;
	private int touchDownY_;
	private int touchDownX_;
	private long systemTime_=0;
	
	private String icon;//绘制到按钮上的图片
	
	// 购物车
	String type;
	static Bitmap cartBitmap;
	
	// 修改输入框的名称
	public String linkage_;
	// 联动的类型，分“加”、“减”（plus和minus）
	public String linkType_;
	// 输入框的最大值
	public String maxValue_;
	// 输入框的最小值
	public String minValue_;
	/**验证登录时传给后台的类型*/
	public String loginType_ ;
	/**单独处理点餐提交订单*/
	public String getJson_;
	/**只有登录和注册按钮有此属性*/
	public String hangType_;
	
	/**
	 * @param context
	 */
	public mButton(Context context, String text, int styleIndex, boolean isSubmenu, boolean isFirstSubmenu, boolean isLastSubmenu) {
		super(context);
		isSubmenu_ = isSubmenu;
		isFirstSubmenu_ = isFirstSubmenu;
		isLastSubmenu_ = isLastSubmenu;
		bv_ = (BaseView) context;
		font_ = new TextPaint();
		font_.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_MEDIUM));
		font_.setTypeface(Typeface.DEFAULT_BOLD);
		this.setFocusable(true);
		this.setFocusableInTouchMode(true);
		this.setTextColor(BaseView.COLOR_BUTTONTEXT);
		
		setText(text);
		styleIndex_ = styleIndex;

	}

	/**
	 * @param context
	 * @param resourceId
	 * @return
	 */
	public static Bitmap[] createImg(Context context, int resourceId) {
		Bitmap[] buttonImg = new Bitmap[3];
		Bitmap buttonAllImg = null;
		buttonAllImg = ConstantRepository.decodeBitmap(context.getResources(), resourceId);
		if (buttonAllImg == null) {
			return null;
		}
		int width = buttonAllImg.getWidth() / 3;
		int height = buttonAllImg.getHeight();
		buttonImg[NORMAL_IMG] = Bitmap.createBitmap(buttonAllImg, width, 0, width, height);
		buttonImg[DOWN_IMG] = Bitmap.createBitmap(buttonAllImg, width << 1, 0, width, height);
		buttonImg[FOCUS_IMG] = Bitmap.createBitmap(buttonAllImg, 0, 0, width, height);

		if (buttonAllImg != null && !buttonAllImg.isRecycled()) {
			buttonAllImg.recycle();
		}
		buttonAllImg = null;
		return buttonImg;
	}


	/**
	 * 设置是否需要滚动文字
	 * */
	void setRoll() {
		BaseView.setTypeFace(font_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
		if (width_ < font_.measureText((String) getText())) {
			isRollNotStopB_ = true;
		} else {
			isRollNotStopB_ = false;
		}
	}

	/**
	 * @param buttonWidth
	 * @param buttonHeight
	 */
	private void createButton(int buttonWidth, Bitmap activeButton, Bitmap inactiveButton, Bitmap downButton) {
		try {
			focusButton_ = Utils.makeButton(activeButton, buttonWidth);
			upButton_ = Utils.makeButton(inactiveButton, buttonWidth);
			downButton_ = Utils.makeButton(downButton, buttonWidth);

		} catch (Exception ex) {
		}
	}

	/**
	 * @param text
	 */
	public void setText(String text) {
		super.setText(text);
	}
	
	public String getContentText() {
		return (String) super.getText();
	}

	public void setContentText(String text) {
		// TODO Auto-generated method stub
		this.setText(text);
	}

	// 响应点击该按钮的执行操作
	public void pointerPressed(BaseView bv) {
		if (!isFocusable() || getVisibility() != View.VISIBLE)
			return;
		try {
			if (listener_ != null)
				listener_.componentAction(this, (BaseView) this.getContext());
			else if (bv.listener_ != null)
				bv.listener_.componentAction(this, (BaseView) this.getContext());
		} catch (Exception ex) {
			Utils.printException(ex);
		}
	}
	
	/**
	 * 响应按键按下操作
	 * */
	public boolean onKeyDown(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			isDown_ = true;
			this.requestFocus();
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	/**
	 * 响应按键按下操作
	 * */
	public boolean onKeyUp(int keyCode, KeyEvent event) {
		switch (keyCode) {
		case KeyEvent.KEYCODE_DPAD_CENTER:
			isDown_ = false;
			if (clickedColor_ != 0) {
				setTextColor(clickedColor_);
			}
			this.pointerPressed(bv_);
			break;
		default:
			return super.onKeyDown(keyCode, event);
		}
		return true;
	}

	public void setFocus(boolean isFocus, int keyCode) {
		focus_ = isFocus;
	}

	/**
	 * 响应触摸
	 * */
	public boolean onTouchEvent(MotionEvent event) {
		if (!isEnabled())
			return true;

		int touchEvent = event.getAction();
		int x = (int) event.getX();
		int y = (int) event.getY();

		switch (touchEvent) {
		case MotionEvent.ACTION_DOWN:
			touchDownX_ = (int) event.getX();
			touchDownY_ = (int) event.getY();
			isDown_ = true;
			this.requestFocus();
			invalidate();
			break;
		case MotionEvent.ACTION_UP:
			systemTime_=System.currentTimeMillis()-systemTime_;
			if (isDown_ == true || (Math.abs(x - touchDownX_) < 10 && Math.abs(y - touchDownY_) < 10)) {
				if ((touchDownX_ >60 && isSubmenu_)||!isSubmenu_){
					isDown_ = false;
					if (clickedColor_ != 0) {
						setTextColor(clickedColor_);
					}
					invalidate();
					if (isSubmenu_){
						bv_.currentItem_ = bv_.tabBar_.indexOfContentChild(this);
					}
					if(systemTime_>1000){
						pointerPressed(bv_);
					} 
				}
			}
			break;
		case MotionEvent.ACTION_MOVE:
			if (Math.abs(x - touchDownX_) > 3 || Math.abs(y - touchDownY_) > 3) {
				isDown_ = false;
				invalidate();
			}
			break;
		default:
			isDown_ = false;
			invalidate();
			return super.onTouchEvent(event);
		}
		return true;
	}

	protected void onDraw(Canvas canvas) {
		if (isSubmenu_) {
			onDrawSubmenu(canvas);
		} else {
			onDrawNormal(canvas);
		}

	}

	/**
	 * 绘制二级界面的label
	 * 
	 * @param g
	 */
	private void onDrawSubmenu(Canvas g) {
		// TODO Auto-generated method stub
		final String text = this.getText().toString();
		final Paint paint = this.getPaint();
		// 文字和控件右端的距离
		float scale = Utils.SCALEDATE_W * Utils.DM_DENSITY;
		float space = 30 * scale;
		paint.setColor(0xFF000000);
		paint.setTextSize(Utils.getScaledValue(ConfigManager.SIZE_SMALL));
		if (isDown_) {
			if (isFirstSubmenu_) {
				g.drawBitmap(BACKGROUNDSEL1, 0, 0, this.getPaint());
			} else if (isLastSubmenu_) {
				g.drawBitmap(BACKGROUNDSEL3, 0, 0, this.getPaint());
			} else {
				g.drawBitmap(BACKGROUNDSEL2, 0, 0, this.getPaint());
			}
		} else {
			if (isFirstSubmenu_) {
				g.drawBitmap(BACKGROUND1, 0, 0, this.getPaint());
			} else if (isLastSubmenu_) {
				g.drawBitmap(BACKGROUND3, 0, 0, this.getPaint());
			} else {
				g.drawBitmap(BACKGROUND2, 0, 0, this.getPaint());
			}
		}
		g.drawText(text, space, (BACKGROUND2.getHeight() + ConfigManager.SIZE_SMALL * scale)/2 - 2, paint);
		if (iconBitmap!=null) {
		    g.drawBitmap(iconBitmap, BACKGROUND2.getWidth() - iconBitmap.getWidth() - space-4, 
		    		(BACKGROUND2.getHeight() - iconBitmap.getHeight())/2, 
		    		this.getPaint());
		}
	}

	// 按钮的普通绘制方法
	private void onDrawNormal(Canvas canvas) {
		if (focusButton_ != null) {
			Bitmap temp = null;
			if (isDown_) {
				temp = downButton_;
			} else if (!this.isEnabled()) {
				temp = downButton_;
			} else if (isFocused() || this.focus_) {
				temp = focusButton_;
			} else {
				temp = upButton_;
			}
			try {
				canvas.drawBitmap(temp, 0, 0, font_);
			} catch (Exception e) {
				Utils.printException(e);
			}
		} else {
			Drawable[] db = null;
			if (isDown_) {
				db = downDrawable_;
			} else if (isFocused() || this.focus_) {
				db = focusDrawable_;
			} else if (!this.isEnabled()) {
				db = focusDrawable_;
			} else {
				db = upDrawable_;
			}
			try {
				for (Drawable d : db) {
					d.draw(canvas);
				}
			} catch (Exception e) {
				Utils.printException(e);
			}
		}
		drawText(canvas);
	}

	/**
	 * 绘制文本
	 * @param canvas
	 */
	protected void drawText(Canvas canvas) {
		int color = textColor_;
		if (textColor_ == 0) {
			color = getCurrentTextColor();
		}
		String text = (String) getText();

		float y = top_ + height_ / 2 + font_.getTextSize() * 0.5f / 2;
		if (isRollNotStopB_) {
			BaseView.setTypeFace(font_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
			StringTicker.instance().drawMoveStr(this, canvas, width_, font_, color, text, left_, (int) y);
		} else {
			font_.setColor(color);
			// 设置字体非抗锯齿效果，使字体边界更平滑
			font_.setAntiAlias(true);
			BaseView.setTypeFace(font_, cssStyle_ != null ? cssStyle_.fontWeight_ : null);
			int x = left_ + ((width_ - (int) font_.measureText(text)) >> 1);
			canvas.drawText(text, x, y, font_);
		}
	}

	public void shrinkWidth() {
		// TODO Auto-generated method stub

	}

	public void cleanText() {
		// TODO Auto-generated method stub

	}

	public void mould() {
		/*
		 * set button width and height.
		 */
		if (width_ <= 0) {
			// means it has not been set manually.
			width_ = Utils.screenWidth_;
		}
		if (cssStyle_ != null && cssStyle_.width_ > 0) {
			// it should be as the CSS style referred.
			width_ = cssStyle_.width_;
		}
		if (cssStyle_ != null && cssStyle_.fontSize_ > 0) {
			font_.setTextSize(cssStyle_.fontSize_);
		}
		if (cssStyle_ != null && cssStyle_.fgColor_ != 0) {
			textColor_ = cssStyle_.fgColor_;
		}
		// check if the button image was referred.
		int resId = searchButtonImgResId();
		// create button.
		Bitmap[] btImg = null;
		btImg = createImg(bv_, resId);
		if (btImg == null) {
			resId = -1;
		}
		// 如果显示的是二级菜单界面，在此判断里，做好图片等初始化处理工作
		if (isSubmenu_ && BACKGROUND1 == null) {
			BACKGROUND1 = Utils.getScaledBitmap(this.getResources(), R.drawable.submenufirst);
			BACKGROUNDSEL1 = Utils.getScaledBitmap(this.getResources(), R.drawable.submenuselfirst);
			BACKGROUND2 = Utils.getScaledBitmap(this.getResources(), R.drawable.submenu);
			BACKGROUNDSEL2 = Utils.getScaledBitmap(this.getResources(), R.drawable.submenusel);
			BACKGROUND3 = Utils.getScaledBitmap(this.getResources(), R.drawable.submenulast);
			BACKGROUNDSEL3 = Utils.getScaledBitmap(this.getResources(), R.drawable.submenusellast);
		}
		if (isSubmenu_) {
			// 如果是二级菜单,怎直接以图片宽高定区域
			if (isLastSubmenu_) {
				height_ = BACKGROUND3.getHeight();
			} else {
				height_ = BACKGROUND2.getHeight();
			}
			width_ = BACKGROUND2.getWidth();
		} else {
			if (resId > -1) {
				if (isSinglePng) {
					downButton_ = btImg[DOWN_IMG];
					focusButton_ = btImg[FOCUS_IMG];
					upButton_ = btImg[NORMAL_IMG];
					height_ = focusButton_.getHeight();
					width_ = focusButton_.getWidth();
				} else {
					createButton(width_, btImg[FOCUS_IMG], btImg[NORMAL_IMG], btImg[DOWN_IMG]);
					int size = btImg.length;
					for (int i = 0; i < size; i++) {
						if (btImg[i] != null && !btImg[i].isRecycled()) {
							btImg[i].recycle();
						}
						btImg[i] = null;
					}
					btImg = null;
					height_ = focusButton_.getHeight();
				}
			} else {
				int upColor = DEFAULT_BUTTON_UP_COLOR;
				if (cssStyle_ != null && cssStyle_.bgColor_ != 0) {
					upColor = cssStyle_.bgColor_;
				}
				int downColor = DEFAULT_BUTTON_DOWN_COLOR;
				if (pseudoStyle_ != null && pseudoStyle_.bgColor_ != 0) {
					downColor = pseudoStyle_.bgColor_;
				}
				int borderColor = 0;
				if (cssStyle_ != null && cssStyle_.borderColor_ != 0) {
					borderColor = cssStyle_.borderColor_;
				}
				height_ = ((int) font_.getTextSize()) << 1;
				Rect rect = new Rect(0, 0, width_, height_);
				upDrawable_ = DrawableFactory.create(styleIndex_, rect, upColor, borderColor, false);
				downDrawable_ = DrawableFactory.create(styleIndex_, rect, downColor, borderColor, true);
				focusDrawable_ = DrawableFactory.create(styleIndex_, rect, DEFAULT_BUTTON_FOCUS_COLOR, borderColor, false);
			}
		}
		LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(width_, height_);
		if (selfLayout_ != null) {
			BaseView.removeViewsStepByStep(selfLayout_, this);
		}
		selfLayout_ = BaseView.createSelfLayout(bv_, lp, cssStyle_, this);
		// #ifdef Android1.0
//@		 lp.topMargin = 5;
		// #endif
		if (isSubmenu_) {
			// 如果是二级菜单，则设置topMargin为0
			lp.bottomMargin = -10;
		} else {
			lp.topMargin = 4;
			lp.bottomMargin = 4;
		}
		setLayoutParams(lp);
		// 设置文字滚动
		setRoll();
	}

	/**
	 * @return
	 */
	private int searchButtonImgResId() {
		int resId = -1;
		String imgName = null;
		if (null != cssStyle_ && cssStyle_.bgImageUrl_ != null) {
			if (cssStyle_.bgImageUrl_.startsWith("local:")) {
				imgName = cssStyle_.bgImageUrl_.substring("local:".length());
				if (imgName.toLowerCase().startsWith("bluebutton.png") || imgName.toLowerCase().startsWith("bluembutton.png")) {
					resId = R.drawable.bluebutton;
				}
			}
		}
		return resId;
	}

	public void setCmpHeidht(int height) {
		// TODO Auto-generated method stub

	}

	public void setCmpWidth(int width) {
		// TODO Auto-generated method stub

	}

	public void setCssStyle(CssStyle style) {
		cssStyle_ = style;
	}

	public View getCmpView() {
		if (selfLayout_ != null) {
			return selfLayout_;
		}
		return this;
	}

	public int getCmpHeight() {
		return height_;
	}

	public int getCmpWidth() {
		// TODO Auto-generated method stub
		return width_;
	}

	public void setInTable(boolean inTable) {
		isInTable_ = inTable;
	}

	public boolean isInTable() {
		return isInTable_;
	}

	public CssStyle getCssStyle() {
		return cssStyle_;
	}

	public void releaseResource(View view) {
		// TODO Auto-generated method stub
		if (isSubmenu_) {
			if (null != BACKGROUND1 && !BACKGROUND1.isRecycled())
				BACKGROUND1.isRecycled();
			if (null != BACKGROUNDSEL1 && !BACKGROUNDSEL1.isRecycled())
				BACKGROUNDSEL1.isRecycled();
			if (null != BACKGROUND2 && !BACKGROUND2.isRecycled())
				BACKGROUND2.isRecycled();
			if (null != BACKGROUNDSEL2 && !BACKGROUNDSEL2.isRecycled())
				BACKGROUNDSEL2.isRecycled();
			if (null != BACKGROUND3 && !BACKGROUND3.isRecycled())
				BACKGROUND3.isRecycled();
			if (null != BACKGROUNDSEL3 && !BACKGROUNDSEL3.isRecycled())
				BACKGROUNDSEL3.isRecycled();
			
			BACKGROUND1 = null;
			BACKGROUNDSEL1 = null;
			BACKGROUND2 = null;
			BACKGROUNDSEL2 = null;
			BACKGROUND3 = null;
			BACKGROUNDSEL3 = null;
		}
		// cssStyle_ = null;
		// pseudoStyle_ = null;
		// attrName_ = null;
		// attrValue_ = null;
		// buttonType_ = null;
		// font_ = null;
		// listener_ = null;
		// accessory_ = null;
		// buttonAction_ = null;
		// upDrawable_ = null;
		// downDrawable_ = null;
		// focusDrawable_ = null;
		// selfLayout_ = null;

		if (null != focusButton_ && !focusButton_.isRecycled()) {
			focusButton_.recycle();
		}
		focusButton_ = null;
		if (null != upButton_ && !upButton_.isRecycled()) {
			upButton_.recycle();
		}
		upButton_ = null;
	}

	public void setForm(FormLayout formLayout) {
		// TODO Auto-generated method stub
		formLayout_ = formLayout;
	}

	public FormLayout getForm() {
		// TODO Auto-generated method stub
		return formLayout_;
	}

	@Override
	public void setEncrypt(String encrypt) {
		// TODO Auto-generated method stub
		isEncrypt_ = encrypt;
	}

	public String getIcons() {
		return icon;
	}

	public void setIcons(String icon) {
		int iconId = Utils.getResourceByReflect(icon);
		if (iconId != 99){
			iconBitmap = Utils.getScaledBitmap(this.getResources(), iconId);
		}
		this.icon = icon;
	}

}
